package com.earl.common.util;

import com.earl.common.constant.SystemConstant;
import com.earl.common.enums.Lang;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Optional;

/**
 * 用户上下文
 */
public class UserContextHolder {

    private ThreadLocal<Map<String, Object>> threadLocalUser;


    private UserContextHolder() {
        this.threadLocalUser = new ThreadLocal<>();
    }

    /**
     * 创建实例
     *
     * @return
     */
    public static UserContextHolder getInstance() {
        return SingletonHolder.sInstance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        private static final UserContextHolder sInstance = new UserContextHolder();
    }

    /**
     * 用户上下文中放入信息
     *
     * @param map
     */
    public void setContext(Map<String, Object> map) {
        threadLocalUser.set(Optional.ofNullable(map).orElse(Maps.newHashMap()));
    }

    /**
     * 获取上下文中的信息
     *
     * @return
     */
    public Map<String, Object> getContext() {
        return threadLocalUser.get();
    }

    /**
     * 获取上下文中的用户名
     *
     * @return
     */
    public String getUsername() {
        //return Optional.ofNullable(threadLocal.get()).orElse(Maps.newHashMap()).get("user_name");
        return (String) Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault("username", "default_name");
    }

    /**
     * jwt标识
     *
     * @return
     */
    public String getJwtId() {
        return String.valueOf(Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault("jti", ""));
    }

    /**
     * 真实请求ip
     *
     * @return
     */
    public String getRequestIp() {
        return String.valueOf(Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault(SystemConstant.HEADER_REQUEST_IP, ""));
    }

    /**
     * 局域网ip标识
     *
     * @return
     */
    public String getHostIp() {
        return String.valueOf(Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault(SystemConstant.HEADER_HOST_IP, ""));
    }

    /**
     * 语言
     *
     * @return
     */
    public String getLang() {
        return String.valueOf(Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault(SystemConstant.HEADER_SFC_LANG, Lang.zh.name()));
    }

    /**
     * 姓名
     *
     * @return
     */
    public String getName() {
        return String.valueOf(Optional.ofNullable(threadLocalUser.get()).orElse(Maps.newHashMap()).getOrDefault(SystemConstant.HEADER_NAME, ""));
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocalUser.remove();
    }

}
